var config = {};
var current_card = {};
var decks = [];
var current_deck = 0;
var locations = {};

function loadNextDeck() {
	for (var i = 0, j = decks.length; i < j; i++) {
		if (decks[i].loaded === false) {
			self.port.emit('load_deck', decks[i]);
			break;
		}
	}
}

function displayNextCard() {
	var found = false;
	var allDecksLoaded = true;
	// Loop through the decks from end-to-end beginning with current_deck
	// For example, if we have 9 decks (decks.length == 9), and current_deck
	// is 5, this loop will start with current_deck of 6, 7, 8, 0, 1, 2, 3, 4, 5
	for (var i = 0, j = decks.length; i < j; i++) {
		var next_deck = (current_deck + i + 1) % decks.length;
		if (decks[next_deck].loaded) {
			if (decks[next_deck].cards.length > 0) {
				current_deck = next_deck;
				var next_card = (decks[current_deck]['current_card'] + 1) % decks[current_deck].cards.length;
				decks[current_deck]['current_card'] = next_card;
				current_card = decks[current_deck].cards[next_card];
				displayCard(current_card,'question');
				if (next_card == decks[current_deck].cards.length) {
					// Got to the end of this deck, reload
					decks[current_deck].loaded = false;
					loadNextDeck();
				}
				found = true;
				break;
			}
		} else {
			allDecksLoaded = false;
		}
	}
	if (found === false) {
		if (allDecksLoaded) {
			showHelp('no_cards_found');
		} else {
			newHtml('main','Loading...');
			setTimeout(displayNextCard,1000);
		}
	}
}

function hideAll() {
	$('.hideAll').hide();
}
function newHtml(containerElementId, html) {
	el = $('#' + containerElementId);
	el.hide();
	el.html(html);
	el.find('.siteName').html(config.siteName);
	el.find('.siteURL').click(function(e){
		e.stopPropagation();
		e.preventDefault();
		var data = {};
		data.href = $(this).attr('href');
		self.port.emit('linkClicked',data);
	});
	el.show();
}
function showHelp(helpFor) {
	var helpHtml = config['help_' + helpFor];
	$('#main').hide();
	$('#menubar').hide();
	newHtml('helpText',helpHtml);
	$('#helpText').parent().show();
}
function hideHelp() {
	$('#helpText').parent().hide();
	$('#main').show();
	$('#menubar').show();
}
function getSelectedValue(selector) {
    var selectedIndex = $(selector).attr('selectedIndex');
	if (typeof(selectedIndex) == 'undefined') {
		selectedIndex = 0;
	}
    var sel = $(selector).get(0);
    var val = sel.options[selectedIndex].value;
    return val;
}
// This function display the given side (question / answer) of the card.
// The value for whichSide is 'question' or 'answer'
function displayCard(json,whichSide) {
	newHtml('main',config.card_html);
	current_card = json;
	current_card['displaying'] = whichSide;
	$('#plugin_question').html(json[whichSide]);
	if (whichSide == 'question') {
		current_card.shown = current_card.shown + 1;
		self.port.emit('record_entry_displayed',current_card);
	}
	$('#deck_title').html(decks[current_deck].title);
}

$('body').delegate('#loginFormHelpLink','click', function(e){
	showHelp('loginForm');
});

$('body').delegate('.disable_plugin', 'click', function(e) {
	e.stopPropagation();
	e.preventDefault();
	$(this).mouseout();
	var minutes = 30;
	var text = $.trim($(this).text());
	if (text == '30 minute') {
		minutes = 30;
	} else if (text == '1 hour') {
		minutes = 60;
	} else if (text == '2 hours') {
		minutes = 120;
	} else if (text == '4 hours') {
		minutes = 240;
	} else if (text == '8 hours') {
		minutes = 480;
	}
	self.port.emit('disable', {'minutes': minutes});
	return false;
});

$('body').delegate('#info_btn', 'mouseover', function(e) {
	var hint_container = $('<div id="plugin_card_hint"></div>');
	var tags_html = "";
	if (current_card.tags.length) {
		for (var i = 0, j = current_card.tags.length; i < j; i++) {
			tags_html = tags_html + current_card.tags[i] + '<br/>';
		}
		tags_html = 'This card has the following tags:<br/>' + tags_html;
	} else {
		tags_html = "This entry has not been tagged";
	}
	hint_container.html(tags_html);
	hint_container.appendTo('#plugin_question');
});

$('body').delegate('#info_btn', 'mouseout', function(e) {
	$('#plugin_card_hint').remove();
});

$('body').delegate('#next_btn', 'click', function(e) {
	e.stopPropagation();
	e.preventDefault();
	displayNextCard();
	return false;
});

$('body').delegate('#flip_btn','click', function(e) {
	if (current_card['displaying'] == 'question') {
		displayCard(current_card,'answer');
		current_card.wrong = current_card.wrong + 1;
		self.port.emit('peek', current_card);
	} else {
		displayCard(current_card,'question');
	}
});

$('body').delegate('#menu_change_location','click',function(e) {
	e.stopPropagation();
	e.preventDefault();
	$('#menu_change_location').mouseout();
	self.port.emit('change_location_clicked', {});
	return false;
});

$('body').delegate('#menu_mark_not_applicable', 'click', function(e) {
	e.stopPropagation();
	e.preventDefault();
	$('#menu_mark_not_applicable').mouseout();
	self.port.emit('mark_not_applicable', current_card);
	return false;
});

$('body').delegate('#change_location_btn', 'click', function(e) {
	e.preventDefault();
	e.stopPropagation();
	var p = {};
	p.selected_location_key = getSelectedValue('#change_location_select');
	self.port.emit('set_location', p);
	return false;
});

$('body').delegate('#loginBtn', 'click', function(e) {
	e.stopPropagation();
	e.preventDefault();
	var d = {};
	d.username = $('#username').val();
	d.md5password = $.md5($('#password').val()); // hex-encoded
	self.port.emit('loginBtnClicked', d);
});

$('.dismissHelpText').click(function() {
	hideHelp();
});

self.port.on('load_deck_done', function(json) {
	for (var i = 0, j = decks.length; i < j; i++) {
		if (decks[i].key === json.deck_key) {
			decks[i].cards = json.cards;
			decks[i].loaded = true;
			// If this deck does not have any card, load the next deck immediately
			// so that the user does not have to stare at the loading screen for 5 seconds
			var timeoutDuration = 5000;
			if (json.cards.length == 0) {
				timeoutDuration = 10;
			}
			setTimeout(loadNextDeck,timeoutDuration);
		}
	}
	
});

self.port.on('display_next_card', function(p) {
	displayNextCard();
});

self.port.on('display_locations', function(json) {
	var locations = json.locations;
	if (locations.length) {
		$('#main').html(config.changeLocation_html);
		for (var i = 0, j = locations.length; i < j; i++) {
			var selected = '';
			if (locations[i][0] == config.current_location_key) {
				selected = 'selected="selected"';
			}
			var option_html = '<option value="' + locations[i][0] + '" ' + selected + '>' + locations[i][1] + '</option>';
			$('#change_location_select').append(option_html);
		}
	} else {
		showHelp('no_locations_found');
	}
	$('#menu_change_location').mouseout();
});

self.port.on('showLoginForm', function(json) {
	config = json;
	$('#menubar').hide();
	newHtml('main',config.loginForm);
	$('#username').watermark('watermark','Username');
	$('#password').watermark('watermark','Password');
});

self.port.on('initialize', function(json) {
	plugin_menu = new menu.dd('plugin_menu');
	plugin_menu.init('menu');
});
self.port.on('loginSuccess', function(json) {
	config.locations = json.locations; // for when the user want to change location
	hideHelp();
	config.username = json.username;
	config.md5password = json.md5password;
	config = json.config;
	if (json.decks.length > 0) {
		var first_deck_key = json.decks[0][0];
		decks = [];
		current_deck = 0;
		for (var i = 0, j = json.decks.length; i < j; i++) {
			var deck_key = json.decks[i][0];
			var deck_title = json.decks[i][1];
			decks[decks.length] = {
				'key': deck_key,
				'title': deck_title,
				'loaded': false,
				'current_card': 0
			};
		}
		decks[0].loaded = true;
		decks[0].cards = json.cards;
		displayNextCard();
		// If this deck does not have any card, load the next deck immediately
		// so that the user does not have to stare at the loading screen for 5 seconds
		var timeoutDuration = 5000;
		if (json.cards.length == 0) {
			timeoutDuration = 10;
		}
		setTimeout(loadNextDeck,timeoutDuration);
	} else {
		showHelp('no_decks_found');
	}
});

self.port.on('loginFailed', function(json) {
	showHelp('loginFailed');
});

